// pages/biz/recommend/recommend.js
//引入请求接口文件
import Serv from './recommendServ';
//引入顾问接口文件
import Serv1 from '../selectAdviser/selectAdviserServ';
var regeneratorRuntime = require("../../../lib/js/runtime-module.js")
import Config from "../../../utils/config.js"
//获取应用实例
const app = getApp()
import Request from "../../../utils/request.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bindwallet: null,
    show: false,
    opacity: 'rgba(255,255,255,0)',
    btnDisable: false,
    // 控制多行输入框显示
    showTxArea: true,
    gender: ' ',
    appoint: false,
    // 房源
    houseSource: [],
    counselorData:[],
    //二级给一级的推荐
    counselorList:{},
    //选择的美房
    recmBuildValue: "",
    //提交参数
    query: {
      //客户-xx
      customerName: "",
      //性别
      customerSex: "1",
      customerMobile: "",
      //项目id
      projectId: '',
      //推荐人-xx
      mobile: '',
      name: '',
      //推荐身份证
      userIdCardNum: '',
      userWalletId: "",
      counselorId: "",
      //顾问手机号
      counselorMobile: "",
      //顾问姓名
      counselorName: "",
      //意向房型
      intention_house_type:'',
      //意向面积
      intention_area:'',
    }, houseType: [
      { name: '二室', value: '两房一厅' },
      { name: '三室', value: '三房两厅' },
      { name: '四室', value: '四房两厅' },
    ],
    areaType: [
      { name: '90m²以下', value: '60平米以下,61-90平米' },
      { name: '90-120m²', value: '91-100平米,101-120平米' },
      { name: '120m²以上', value: '121-144平米' },
    ],
  },

  //显示自定义组件
  showSelectBuild() {
    let {query,must} = this.data
    if(must){
      wx.showToast({
        title: '不可选择美房',
        icon:'none'
      })
      return false
    }
    this.setData({
      showTxArea: false,
      query:{
        ...query,
        counselorName: "",
        counselorMobile: "",
      },
      dviser: null,
      adviserIndex:null
    })
    this.buildings.showModal()
  },

  // 选择楼盘项目
  selectBuild(e) {
    let {
      query
    } = this.data;
    console.log(e.detail, "code")
    this.setData({
      query: { ...query,
        productId: e.detail.value,
        projectId: e.detail.code
      },
      showTxArea: true,
      recmBuildValue: e.detail.label
    })
   this.getCounselor(e.detail.value);
    this.counselorAction(e.detail.value);
  },
  //关闭选择楼盘
  hideModal(e){
    console.log(e)
    this.setData({ showTxArea: e.detail.show})
    this.selectBuild(e)
  },
  async counselorAction(id){
    let {success,data} = await Serv.counselorAction(id);
    let {query} = this.data
    if (success){
      this.setData({
        dviser:data.name,
        query:{
          ...query,
          counselorId: data.counselorId,
          counselorMobile: data.mobile,
          counselorName: data.name
        }
      })
    }
  },

  // 选择顾问
  selectAviser() {
    let {
      query, adviserIndex=null
    } = this.data;
    if (!query.productId) return wx.showToast({
      title: '请选择美房',
      icon: 'none'
    });
    wx.navigateTo({
      url: '/subPackages/pages/selectAdviser/selectAdviser?ProductId=' + query.productId + '&adviserIndex=' + adviserIndex,
    })
  },
  //确定绑定钱包
  confirmwallet() {
    wx.navigateTo({
      url: `/subPackages2/pages/wallet/openWallet/openWallet`,
    });
    this.setData({
      show: true,
    })
  },
  cancelwallet() {
    this.setData({
      show: false,
    })
  },
  // 表单提交,需验证合法性
  async formSubmit(e) {
    let {
      query,
      appoint,
    } = this.data;
    let couData = this.data;
    if (couData.gender == " "){
      wx.showToast({
        title: '请选择性别',
        icon: 'none'
      }) 
       return false ;
    }
    let reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
    if (!query.customerName ||
      query.customerSex === "" ||
      !query.customerMobile ||
      !query.productId ||
      (appoint && !query.counselorId)) {
      wx.showToast({
        title: '请输入必填信息',
        icon: 'none'
      })
      return false;
    }
    if (query.customerMobile.length != 11|| !reg.test(query.customerMobile) ) { // 11位
      wx.showToast({
        title: '手机号输入错误，请重新输入',
        icon: 'none'
      })
      return
    }
    
    
    this.setData({
      btnDisable: true
    })
    if (!appoint) {
      delete query.counselorId;
      delete query.counselorMobile;
      delete query.counselorName;
      // this.getCounselor(query.productId);
      // query.counselorId = couData.counselorData.counselorId;
      // query.counselorName = couData.counselorData.name;
      // query.counselorMobile = couData.counselorData.mobile;
    }
    for (let item in query) {
      if (!query[item] && item != 'customerSex') delete query[item]
      }
      console.log(query, "query");
     query.appId = app.globalData.appId;
    wx.showLoading({
      title: '正在提交',
    })
    let {
      success,
      msg,
      data,
      code,
      extParams
    } = await Serv.referralsCreate(query)
    this.setData({
      btnDisable: false
    })
    wx.hideLoading()
    if(success){
      wx.navigateTo({
        url: `/subPackages2/pages/recommendResult/recommendResult?state=1&name=${query.customerName}&msg=推介成功`,
      })
      if (app.globalData.code.query.id){
        let { success } = await Serv.visitNum({
          id: app.globalData.code.query.id,
          clueId: extParams.clueId,
          type:3
        })
      }
    }else{
      wx.navigateTo({
        url: `/subPackages2/pages/recommendResult/recommendResult?state=2&name=${query.customerName}&msg=${msg}`,
      })
    }
   
  },
  async getCounselor(ProductId) {
    let result = await Serv1.counselorGet(ProductId)
   // let dataQuery = this.data;
    if (result.success && result.rows) {
      let array = result.rows; 
      //随机抽取一个值
      let value = array[Math.round(Math.random() * (array.length - 1))]; 
      console.log(value,"顾问名单");
      // dataQuery.query.counselorId = value.counselorId;
      // dataQuery.query.counselorName = value.counselorName;
      this.setData ({
         counselorData:value
       });
      console.log(this.data.counselorData,"我是随机数据");
    }
  },
  routerGo(e){
    //console.log(e,555)
    wx.navigateTo({
      url: `/subPackages/pages/beautyNotice/beautyNotice`,
    })
  },
  //操作数据
  inputChange(e) {
    let key = e.currentTarget.dataset.key
    let value = e.detail.value;
    console.log()

    if(key=='customerMobile'){
      value = value.replace(/\s*/g,"");
    }
    
    let {
      query,
      appoint
    } = this.data;
    if (key == 'customerSex') {
      this.setData({
        gender: value == 1 ? "male" : "female"
      })
    } else if (key == 'counselorIsSelect') {
      this.setData({
        appoint: !appoint
      })
    }
    if (key != 'counselorIsSelect') {
      console.log(key)
      this.setData({
        query: {
          ...query,
          [key]: value
        }
      })
    }
  },
  //钱包
  async getWallet() {
    const params = {}
    let result = await Serv.walletCenter(params)
    this.setData({
      bindwallet: result.data
    })
    console.log(1, this.data.bindwallet)
  },

  walletType() {
    this.getWallet().then(()=>{
      if (!this.data.bindwallet) {
        this.setData({
          opacity: 'rgba(0,0,0,0.5)',
          show: true,
        })
        //console.log(2, this.data.bindwallet)
      }
    })
   
      // wx.showModal({
      //   title: '提示',
      //   content: '为方便佣金结算，请先开通钱包，后续也可单独开通',
      //   cancelText: '继续推介',
      //   confirmText: '开通钱包',
      //   success: function(res) {
      //     if(res.confirm) {
      //       wx.navigateTo({
      //         url: `/pages/biz/wallet/openWallet/openWallet`,
      //       })
      //     }
      //   }
      // })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    if(options.clueId){
      this.getCustomDetail({clueId: options.clueId})
    }
    if (options.type && options.type==1){
      let {query} = this.data;
      this.setData({
        query: {
          ...query,
          productId: options.productId,
          projectId: options.projectId
        },
        recmBuildValue: options.name
      })
    }
    this.walletType();
    if (options.productId){
      this.getCounselor(options.productId);
      this.getEstateDetail(options.productId, options.mustRecommend)
    }
    if (options.customerName){
      let {query} = this.data;
      this.setData({
        query: {
          ...query,
          customerName: options.customerName
        }
      })
    }
    if (options.customerMobile){
      let {query} = this.data;
      this.setData({
        query: {
          ...query,
          customerMobile: options.customerMobile
        }
      })
    }
  },
  //获取客户详情
  async getCustomDetail(params) {
    let {
      data
    } = await Serv.customDetailGet(params)
    data.extraParams = JSON.parse(data.extraParams)
    console.log(data)
    let {query,gender}=this.data
    query.customerName = data.name
    query.customerSex = data.gender
    query.customerMobile = data.mobile
    query.projectId = data.projectCode
    query.productId= data.productId,
    query.mobile = data.referrerMobile
    query.name = data.referrerName
    query.userIdCardNum = data.userIdCardNum || ''
    query.userWalletId = data.userWalletId || ''
    query.counselorId = data.extraParams.counselorId || ''
    query.counselorMobile = data.counselorMobile || ''
    query.counselorName = data.counselorName || ''
    query.intention_house_type = data.extraParams.intention_house_type || ''
    query.intention_area = data.extraParams.intention_area || ''
    gender=data.gender == 1 ? "male" : "female"

    if(data.extraParams.intention_house_type){
      // houseType: [
      //   { name: '二室', value: '两房一厅' },
      //   { name: '三室', value: '三房两厅' },
      //   { name: '四室', value: '四房两厅' },
      // ],
      let {houseType} = this.data
      houseType.map(ele => {
        if(ele.value==data.extraParams.intention_house_type){
          ele.checked = true
        }
      });
      this.setData({
        houseType
      })
    }
    if(data.extraParams.intention_area){
      // areaType: [
      //   { name: '90m²以下', value: '60平米以下,61-90平米' },
      //   { name: '90-120m²', value: '91-100平米,101-120平米' },
      //   { name: '120m²以上', value: '121-144平米' },
      // ],
      let {areaType} = this.data
      areaType.map(ele => {
        if(ele.value==data.extraParams.intention_area){
          ele.checked = true
        }
      });
      this.setData({
        areaType
      })
    }
    if(data.counselorId){
      this.setData({
        appoint:true,
        dviser:data.counselorName
      })
    }
    this.setData({
      query,
      gender,
      recmBuildValue:data.productName
    })
    console.log(data)
    // statusAttr.map((item,idx)=>{
    //   data.followUpList[idx]? data.followUpList[idx].iconCla = item.iconCla : null
    // })
    // let followUpList = data.followUpList ? [].concat(data.followUpList, statusAttr.splice(data.followUpList.length)) : statusAttr;
    // !data.followUpList && (statusAttr[0].createTime = data.createTime)
    //  console.log(followUpList)
    // this.setData({
    //   customDetail: data
    // })
    // console.log(this.data.customDetail)
    //获取图片
    // this.getEstateDetail(data.productId);
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    //获得selectBuild组件
    this.buildings = this.selectComponent("#buildings");
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
   //房型选择
  houseRadioChange(e) {
    let { query } = this.data;
    this.setData({
      query: {
        ...query,
        intention_house_type: e.detail.value,
      },
    })
  },
  //房型选择
  areaRadioChange(e) {
    let { query } = this.data;
    this.setData({
      query: {
        ...query,
        intention_area: e.detail.value,
      },
    })
  },
  async getEstateDetail(id,must=false){
    let {query} =this.data
    let {data} = await Serv.queryEstateDetail(id)
    this.setData({
      query: {
        ...query,
        productId: data.productId,
        projectId: data.projectId
      },
      recmBuildValue: data.name,
      must
    })
  }
})